import tkinter as tk
from datetime import datetime

# 假设有一个简单的数据模型用于存储任务
tasks = []

def create_task(name, due_date=None):
    task = {'name': name, 'due_date': due_date, 'status': 'To-Do'}
    tasks.append(task)
    update_kanban(columns)

def update_kanban(columns):
    # 清空所有列
    for column in columns.values():
        for widget in column.winfo_children():
            if isinstance(widget, tk.Label):  # 只清除标签，保持标题
                widget.destroy()
    
    # 根据状态重新填充列
    for task in tasks:
        color = 'white' if not task['due_date'] or datetime.now() < task['due_date'] else 'red'
        label = tk.Label(columns[task['status']], text=task['name'], bg=color, relief=tk.RAISED, borderwidth=1)
        label.pack(pady=5, fill='x')

def move_task(event, from_column, to_column, task_label):
    # 找到对应的任务并更新其状态
    for task in tasks:
        if task['name'] == task_label.cget('text'):
            task['status'] = to_column
            break
    # 更新看板
    update_kanban(columns)

def setup_kanban(root):
    # 创建三个列
    global columns
    columns = {
        'To-Do': tk.Frame(root, bg='lightblue'),
        'In Progress': tk.Frame(root, bg='lightgreen'),
        'Done': tk.Frame(root, bg='lightyellow')
    }

    for name, frame in columns.items():
        frame.pack(side=tk.LEFT, padx=10, pady=10, fill=tk.Y)
        tk.Label(frame, text=name, font=('Arial', 14, 'bold')).pack()

    # 设置拖放功能
    for column_name, column in columns.items():
        def on_drag_start(event, column=column_name):
            event.widget._drag_start_x = event.x
            event.widget._drag_start_y = event.y

        def on_drag_motion(event, column=column_name):
            drag_distance_x = event.x_root - event.widget._drag_start_x
            drag_distance_y = event.y_root - event.widget._drag_start_y
            x = event.widget.winfo_x() + drag_distance_x
            y = event.widget.winfo_y() + drag_distance_y
            event.widget.place(x=x, y=y)

        def on_drag_release(event, column=column_name):
            for target_column_name, target_column in columns.items():
                if target_column.winfo_containing(event.x_root, event.y_root) and target_column != column:
                    move_task(event, column, target_column_name, event.widget)
                    event.widget.place_forget()
                    return
            event.widget.place(x=event.widget.winfo_x(), y=event.widget.winfo_y())

        column.bind("<Button-1>", on_drag_start)
        column.bind("<B1-Motion>", on_drag_motion)
        column.bind("<ButtonRelease-1>", on_drag_release)

    # 初始化一些示例任务
    create_task("Design UI", datetime(2023, 10, 1))
    create_task("Write Code", datetime(2023, 10, 15))

    # 更新看板以显示初始任务
    update_kanban(columns)